(function () {
  const body = document.body;
  if (!body) return;

  const currentPage = body.dataset.page || null;
  const desktopNav = document.querySelector('[data-site-nav="desktop"]');
  const mobileNav = document.querySelector('[data-site-nav="mobile"]');
  const brandText = document.querySelector('[data-site-brand-text]');
  const brandAnchor = document.querySelector('[data-site-brand]');
  const icpLabel = document.querySelector('[data-site-icp]');

  const menuBtn = document.getElementById('menuBtn');
  const mobileMenu = document.getElementById('mobileMenu');

  const fallbackNav = [
    { key: 'about', label: '关于我们', route: '/pages/about.html' },
    { key: 'services', label: '业务', route: '/pages/services.html' },
    { key: 'products', label: '互动', route: '/pages/products.html' },
    { key: 'solutions', label: '解决方案/案例', route: '/pages/solutions.html' },
    { key: 'team', label: '团队', route: '/pages/team.html' },
    { key: 'contact', label: '联系我们', route: '/pages/contact.html' }
  ];

  const defaultTheme = {
    palette: {
      primary: '#165DFF',
      accent: '#FF7D00',
      neutral: '#E6E9EF'
    },
    surfaces: {
      page: '#0B0C10',
      nav: '#101F40',
      cube: '#1E40AF',
      gradients: {
        page: { enabled: false, from: '#165DFF', to: '#101F40', angle: 135 },
        nav: { enabled: false, from: '#101F40', to: '#165DFF', angle: 135 },
        cube: { enabled: false, from: '#1E40AF', to: '#0B0C10', angle: 150 }
      }
    },
    text: {
      heading: '#E6E9EF',
      body: '#C6CCDA',
      inverse: '#0B0C10',
      interactive: '#165DFF'
    }
  };

  function normalizeHex(value) {
    const hex = (value || '').trim();
    if (!/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(hex)) return null;
    const raw = hex.slice(1).toUpperCase();
    if (raw.length === 3) {
      return `#${raw[0]}${raw[0]}${raw[1]}${raw[1]}${raw[2]}${raw[2]}`;
    }
    return `#${raw}`;
  }

  function hexToRgb(hex) {
    const raw = hex.startsWith('#') ? hex.slice(1) : hex;
    if (raw.length !== 6) return null;
    const r = parseInt(raw.slice(0, 2), 16);
    const g = parseInt(raw.slice(2, 4), 16);
    const b = parseInt(raw.slice(4, 6), 16);
    if ([r, g, b].some(Number.isNaN)) return null;
    return { r, g, b };
  }

  function hexWithAlpha(color, alpha) {
    const normalized = normalizeHex(color);
    if (!normalized) return null;
    const rgb = hexToRgb(normalized);
    if (!rgb) return null;
    const clamped = Math.min(Math.max(alpha, 0), 1);
    return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${clamped.toFixed(2)})`;
  }

  function mergeTheme(theme) {
    const source = theme && typeof theme === 'object' ? theme : {};
    const paletteSource = Object.assign({}, source.palette || {});
    if (!paletteSource.accent && paletteSource.secondary) {
      paletteSource.accent = paletteSource.secondary;
    }
    if (paletteSource.secondary !== undefined) {
      delete paletteSource.secondary;
    }
    const textSource = Object.assign({}, source.text || {});
    if (!textSource.inverse && textSource.button) {
      textSource.inverse = textSource.button;
    }
    if (textSource.button !== undefined) {
      delete textSource.button;
    }
    const surfacesSource = source.surfaces && typeof source.surfaces === 'object' ? source.surfaces : {};
    const surfaces = Object.assign({}, defaultTheme.surfaces, surfacesSource);
    const defaultGradients = defaultTheme.surfaces.gradients || {};
    const sourceGradients = surfacesSource.gradients && typeof surfacesSource.gradients === 'object' ? surfacesSource.gradients : {};
    const gradients = {};
    Object.keys(defaultGradients).forEach((key) => {
      gradients[key] = Object.assign({}, defaultGradients[key], sourceGradients[key] || {});
    });
    surfaces.gradients = gradients;
    return {
      palette: Object.assign({}, defaultTheme.palette, paletteSource),
      surfaces,
      text: Object.assign({}, defaultTheme.text, textSource)
    };
  }

  function clampAngle(value, fallback = 135) {
    const num = Number(value);
    if (!Number.isFinite(num)) return fallback;
    const normalized = Math.round(num) % 360;
    return normalized >= 0 ? normalized : normalized + 360;
  }

  function getGradientEntry(gradients, key) {
    if (!gradients || !key) return null;
    const entry = gradients[key];
    if (!entry || !entry.enabled) return null;
    const from = normalizeHex(entry.from);
    const to = normalizeHex(entry.to);
    if (!from || !to) return null;
    const defaultAngle = defaultTheme.surfaces.gradients?.[key]?.angle ?? 135;
    const angle = clampAngle(entry.angle, defaultAngle);
    return { from, to, angle };
  }

  function buildGradient(entry) {
    return `linear-gradient(${entry.angle}deg, ${entry.from} 0%, ${entry.to} 100%)`;
  }

  function buildGradientAlpha(entry, alpha = 1) {
    const start = hexWithAlpha(entry.from, alpha) || entry.from;
    const end = hexWithAlpha(entry.to, alpha) || entry.to;
    return `linear-gradient(${entry.angle}deg, ${start} 0%, ${end} 100%)`;
  }

  function applyTheme(theme) {
    const root = document.documentElement;
    if (!root) return;
    const merged = mergeTheme(theme);
    const setVar = (name, value) => {
      if (!value) return;
      root.style.setProperty(name, value);
    };
    const primary = normalizeHex(merged.palette.primary);
    const accent = normalizeHex(merged.palette.accent);
    const neutral = normalizeHex(merged.palette.neutral);
    const pageBg = normalizeHex(merged.surfaces.page);
    const navBg = normalizeHex(merged.surfaces.nav);
    const cubeBg = normalizeHex(merged.surfaces.cube);
    const heading = normalizeHex(merged.text.heading);
    const bodyText = normalizeHex(merged.text.body);
    const inverseText = normalizeHex(merged.text.inverse);
    const interactive = normalizeHex(merged.text.interactive);

    if (primary) {
      setVar('--color-primary', primary);
      setVar('--color-primary-soft', hexWithAlpha(primary, 0.18) || 'rgba(22, 93, 255, 0.18)');
      setVar('--cube-glow-primary', hexWithAlpha(primary, 0.55) || 'rgba(22, 93, 255, 0.55)');
      setVar('--glow-hero', hexWithAlpha(primary, 0.08) || 'rgba(22, 93, 255, 0.08)');
      setVar('--glow-divider', hexWithAlpha(primary, 0.6) || 'rgba(22, 93, 255, 0.6)');
      setVar('--glow-surface', hexWithAlpha(primary, 0.22) || 'rgba(22, 93, 255, 0.22)');
      setVar('--shadow-primary-soft', hexWithAlpha(primary, 0.28) || 'rgba(43, 99, 255, 0.28)');
      setVar('--shadow-primary-strong', hexWithAlpha(primary, 0.34) || 'rgba(43, 99, 255, 0.34)');
    }

    if (accent) {
      setVar('--color-accent', accent);
      setVar('--cube-glow-accent', hexWithAlpha(accent, 0.28) || 'rgba(255, 125, 0, 0.28)');
    }

    if (neutral) {
      setVar('--color-surface-faint', hexWithAlpha(neutral, 0.015) || 'rgba(230, 233, 239, 0.015)');
      setVar('--color-surface-xweak', hexWithAlpha(neutral, 0.02) || 'rgba(230, 233, 239, 0.02)');
      setVar('--color-surface-weak', hexWithAlpha(neutral, 0.03) || 'rgba(230, 233, 239, 0.03)');
      setVar('--color-surface', hexWithAlpha(neutral, 0.04) || 'rgba(230, 233, 239, 0.04)');
      setVar('--color-surface-medium', hexWithAlpha(neutral, 0.05) || 'rgba(230, 233, 239, 0.05)');
      setVar('--color-surface-stronger', hexWithAlpha(neutral, 0.06) || 'rgba(230, 233, 239, 0.06)');
      setVar('--color-surface-strong', hexWithAlpha(neutral, 0.12) || 'rgba(230, 233, 239, 0.12)');
      setVar('--color-border-hairline', hexWithAlpha(neutral, 0.04) || 'rgba(230, 233, 239, 0.04)');
      setVar('--color-border', hexWithAlpha(neutral, 0.22) || 'rgba(230, 233, 239, 0.22)');
      setVar('--color-border-soft', hexWithAlpha(neutral, 0.14) || 'rgba(230, 233, 239, 0.14)');
      setVar('--color-border-glass', hexWithAlpha(neutral, 0.08) || 'rgba(230, 233, 239, 0.08)');
    }

    if (heading) {
      setVar('--color-text-primary', heading);
    }

    if (bodyText) {
      setVar('--color-text-secondary', hexWithAlpha(bodyText, 0.78) || bodyText);
      setVar('--color-text-muted', hexWithAlpha(bodyText, 0.6) || bodyText);
    }

    if (inverseText) {
      setVar('--color-text-inverse', inverseText);
    }

    if (interactive) {
      setVar('--color-interactive', interactive);
    }

    if (pageBg) {
      setVar('--color-bg', pageBg);
      setVar('--surface-overlay', hexWithAlpha(pageBg, 0.85) || 'rgba(11, 12, 16, 0.85)');
    }

    if (navBg) {
      setVar('--site-header-background', hexWithAlpha(navBg, 0.68) || 'rgba(16, 31, 64, 0.68)');
      setVar('--surface-glass', hexWithAlpha(navBg, 0.55) || 'rgba(16, 31, 64, 0.55)');
    }

    if (cubeBg) {
      const start = hexWithAlpha(cubeBg, 0.35) || 'rgba(30, 64, 175, 0.35)';
      setVar('--cube-stage-background', `linear-gradient(160deg, ${start}, rgba(9, 12, 24, 0.9))`);
    }

    const gradients = (merged.surfaces && merged.surfaces.gradients) || {};
    const pageGradient = getGradientEntry(gradients, 'page');
    if (pageGradient) {
      setVar('--color-bg', buildGradient(pageGradient));
      setVar('--surface-overlay', buildGradientAlpha(pageGradient, 0.85));
    }

    const navGradient = getGradientEntry(gradients, 'nav');
    if (navGradient) {
      setVar('--site-header-background', buildGradientAlpha(navGradient, 0.68));
      setVar('--surface-glass', buildGradientAlpha(navGradient, 0.55));
    }

    const cubeGradient = getGradientEntry(gradients, 'cube');
    if (cubeGradient) {
      setVar('--cube-stage-background', buildGradientAlpha(cubeGradient, 0.35));
    }
  }

  applyTheme(defaultTheme);

  function renderNav(list) {
    if (desktopNav) {
      desktopNav.innerHTML = '';
      list.forEach((item) => {
        if (!item.route) return;
        const li = document.createElement('li');
        const a = document.createElement('a');
        a.className = 'site-nav__link';
        a.href = item.route;
        a.textContent = item.label || item.key;
        a.dataset.nav = item.key || '';
        if (item.summary) {
          a.title = item.summary;
        }
        li.appendChild(a);
        desktopNav.appendChild(li);
      });
    }
    if (mobileNav) {
      mobileNav.innerHTML = '';
      list.forEach((item) => {
        if (!item.route) return;
        const a = document.createElement('a');
        a.className = 'mobile-menu__link';
        a.href = item.route;
        a.textContent = item.label || item.key;
        a.dataset.nav = item.key || '';
        if (item.summary) {
          a.title = item.summary;
        }
        mobileNav.appendChild(a);
      });
    }

    if (currentPage) {
      document
        .querySelectorAll(`a[data-nav="${currentPage}"]`)
        .forEach((link) => link.classList.add('is-active'));
    }

    if (mobileMenu) {
      mobileMenu.querySelectorAll('a').forEach((link) => {
        link.addEventListener('click', () => mobileMenu.classList.remove('is-open'));
      });
    }
  }

  function toggleMenu() {
    if (mobileMenu) {
      mobileMenu.classList.toggle('is-open');
    }
  }

  if (menuBtn) {
    menuBtn.addEventListener('click', toggleMenu);
  }

  fetch('/api/content/site', { cache: 'no-store' })
    .then((res) => (res.ok ? res.json() : Promise.reject(res.statusText)))
    .then((site) => {
      applyTheme(site.theme);
      if (site.companyName && brandText) {
        brandText.textContent = site.companyName.replace(/(有限公司)$/u, '').trim() || site.companyName;
      }
      if (brandAnchor && site.homeRoute) {
        brandAnchor.href = site.homeRoute;
      }
      if (icpLabel && site.icpRecord) {
        icpLabel.textContent = site.icpRecord;
      }
      const navItems = Array.isArray(site.navigation) && site.navigation.length ? site.navigation : fallbackNav;
      renderNav(navItems);
    })
    .catch(() => renderNav(fallbackNav));
})();
